package com.shuai.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.shuai.adapter.PlantListAdapter;
import com.shuai.sql.SQL;
import com.shuai.stickynote.EditActivity;
import com.shuai.tool.ClassFactory;
import com.shuai.tool.IDManager;
import com.shuai.stickynote.PlantNote;
import com.shuai.stickynote.R;
import com.shuai.tool.SendTool;
import com.shuai.tool.MyTime;

import java.util.ArrayList;

public class PlantFragment extends Fragment {
//    Fragment的视图
    private View view;
//    日历视图
    public static CalendarView calendarView;
//    左上角的日期视图
    private TextView tv_title;
//    当前选中的年份
    private int myear = 0;
//    用户选中的日期文本
    private String selectDate = "";
//    日期计划的内容
    private String content = "";
//    日期计划的标题
    private String title = "";
    private String firstTitle = "";
//    sql工具
    private SQL sql;
//    日期计划预览列表
    private ListView lv_list;
//    日期计划预览列表适配器
    private PlantListAdapter adapter;
//    日期标记列表
    private ArrayList<Calendar> schemeList = null;

    private ArrayList<PlantNote> data = null;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frgment_plant,container,false);
        init();
        return view;
    }

    private void init() {
//        绑定日历控件
        calendarView = view.findViewById(R.id.calendarView);
//        获取sql工具
        sql = EditActivity.sql;
//        获取当前年份
        myear = calendarView.getCurYear();
//        获取左上角日期视图组件
        tv_title = EditActivity.tv_title;
//        设置日期
        tv_title.setText(getDate());
//        日期视图组件点击事件
        tv_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                显示年份选择视图
                calendarView.showYearSelectLayout(myear);
            }
        });
//        日历组件的月份改变监听
        calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @Override
            public void onMonthChange(int year, int month) {
//                设置日期
                tv_title.setText(year+"年"+month+"月"+calendarView.getCurDay()+"日");
//                改变当前年份
                myear = year;
            }
        });
//        用户点击日历某天的监听器
        calendarView.setOnDateSelectedListener(new CalendarView.OnDateSelectedListener() {
            @Override
            public void onDateSelected(Calendar calendar, boolean isClick) {
                if (isClick){
//                    设置选中当天的日期文本
                    selectDate = calendar.getYear()+"年"+calendar.getMonth()+"月"+calendar.getDay()+"日";
//                    判断是否为今天之前的日期，是则警告是否继续添加，否则显示添加事件对话框
                    if (isBefortDay()) befortDayDialog();
                    else addPlant();
                }
            }
        });
//        绑定日期计划列表视图
        lv_list = view.findViewById(R.id.plant_list);
//        设置适配器
        adapter = new PlantListAdapter(getContext());
        data = getData();
        adapter.replaceAll(data);
        lv_list.setAdapter(adapter);
//        日期计划预览列表点击监听器
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updatePlant(data.get(position));
            }
        });
//        日期计划预览列表长按点击监听器
        lv_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                deleteOrSend(data.get(position));
                return true;
            }
        });
//        标记有计划的日期
        setScheme();
    }
//    从数据库中读取日期计划数据，并排序
    private ArrayList<PlantNote> getData(){
        return sortData(sql.selectPlantByDoing());
    }
//    获取当天格式话日期文本
    public static String getDate(){
        return calendarView.getCurYear()+"年"+calendarView.getCurMonth()+"月"+calendarView.getCurDay()+"日";
    }
//    添加事件
    private void addPlant(){
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_plant_add,null);
        TextView btn_no = dialogView.findViewById(R.id.dialog_plant_btn_no);
        TextView btn_yes = dialogView.findViewById(R.id.dialog_plant_btn_yes);
        TextView btn_next = dialogView.findViewById(R.id.dialog_plant_btn_next);
        final EditText et_content = dialogView.findViewById(R.id.dialog_plant_content);
        final EditText et_title = dialogView.findViewById(R.id.diagog_plant_title);

        final boolean[] isFirstTimeAdd = {true};
        final ArrayList<PlantNote> addData = new ArrayList<>();
        final String day = MyTime.dayStrToTimeStamp(selectDate);
        final String[] group = {findDay(day)};
        title = findTitle(day);

        if (!title.equals("")) et_title.setText(title);

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext()).setView(dialogView)
                .setTitle(selectDate);
        final Dialog dialog = builder.create();
        dialog.setContentView(dialogView);
        dialog.show();

        btn_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                content = et_content.getText().toString();
                if (firstTitle.equals("")) { title = et_title.getText().toString(); }
                else if (!title.equals("")){
                    title = firstTitle;
                    et_title.setText(title);
                }
                if (!content.equals("")){
                    String id = IDManager.getID();
                    if (isFirstTimeAdd[0]){
                        if (group[0].equals("")) group[0] = id;
                        isFirstTimeAdd[0] = false;
                    }
                    PlantNote plantNote = new PlantNote(id, MyTime.getCurrentTimeOfStamp(),
                            day,content,title,group[0],0,0);
                    addData.add(plantNote);
                    et_content.setText("");
                }
            }
        });
        btn_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                content = et_content.getText().toString();
                title = et_title.getText().toString();
                if (!title.equals("")) firstTitle = title;
                if (!content.equals("")){
                    String id = IDManager.getID();
                    if (isFirstTimeAdd[0]) {
                        if (group[0].equals("")) group[0] = id;
                        isFirstTimeAdd[0] = false;
                    }
                    PlantNote plantNote = new PlantNote(id, MyTime.getCurrentTimeOfStamp(),
                            day,content,title,group[0],0,0);
                    addData.add(plantNote);
                }
                if (!isFirstTimeAdd[0]){
                    for (PlantNote plant:addData) {
                        sql.insertPlant(plant);
                    }
                    Toast.makeText(getContext(), "已保存~", Toast.LENGTH_SHORT).show();
                    onResume();
                }else Toast.makeText(getContext(), "内容为空，取消保存！", Toast.LENGTH_SHORT).show();
                firstTitle = "";
                dialog.dismiss();
            }
        });
    }
    private String findDay(String day){
        for (int i = 0; i < data.size(); i++){
            if (data.get(i).getDay().equals(day)) return data.get(i).getGroup();
        }
        return "";
    }
    private String findTitle(String day){
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getDay().equals(day)) return data.get(i).getTitle();
        }
        return "";
    }
//    修改事件
    private void updatePlant(final PlantNote plant){
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_plant_add,null);
        TextView btn_no = dialogView.findViewById(R.id.dialog_plant_btn_no);
        TextView btn_yes = dialogView.findViewById(R.id.dialog_plant_btn_yes);
        TextView btn_next = dialogView.findViewById(R.id.dialog_plant_btn_next);
        btn_next.setVisibility(View.GONE);
        btn_yes.setText("修改");
        final EditText et_content = dialogView.findViewById(R.id.dialog_plant_content);
        final EditText et_title = dialogView.findViewById(R.id.diagog_plant_title);

        et_title.setText(plant.getTitle());
        et_content.setText(plant.getContent());
        
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext()).setView(dialogView)
                .setTitle(selectDate);
        final Dialog dialog = builder.create();
        dialog.setContentView(dialogView);
        dialog.show();
        btn_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btn_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                content = et_content.getText().toString();
                title = et_title.getText().toString();
                if (!content.equals("")){
                    plant.setTitle(title);
                    plant.setContent(content);
                    sql.updatePlant(plant);
                    Toast.makeText(getContext(), "修改完成！已保存~", Toast.LENGTH_SHORT).show();
                    onResume();
                }else {
                    Toast.makeText(getContext(), "内容为空，取消修改！若需要删除请长按呼出删除选项。", Toast.LENGTH_SHORT).show();
                }
                dialog.dismiss();
            }
        });
    }
//    判断是否为今天之前的日期
    private boolean isBefortDay(){
        int today = MyTime.toTimeStampForInt(MyTime.getCurrentTime());
        int selectDay = MyTime.dayStrToTimeStampForInt(selectDate);
        return today > selectDay ? true : false;
    }
//    选中今天之前日期的对话框
    private void befortDayDialog(){
        new AlertDialog.Builder(getContext())
                .setTitle("警告")
                .setMessage("您选择的日期比今天还早噢~\n您要继续操作码？")
                .setNegativeButton("继续", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        addPlant();
                    }
                })
                .setPositiveButton("取消", null)
                .create().show();
    }
//    标记有计划的日期
    private void setScheme(){
        if (schemeList == null) schemeList = new ArrayList<>();
        ArrayList<PlantNote> data = getData();
        int y, m, d;
        if (data != null){
            for (int i = 0; i < data.size(); i++){
                y = MyTime.getYear(data.get(i).getDay());
                m = MyTime.getMonth(data.get(i).getDay());
                d = MyTime.getDay(data.get(i).getDay());
                if (!data.get(i).getTitle().equals(""))
                    schemeList.add(getSchemeCalendar(y,m,d,0xFF40db25,String.valueOf(data.get(i).getTitle().charAt(0))));
                else schemeList.add(getSchemeCalendar(y,m,d,0xFF40db25,String.valueOf(data.get(i).getContent().charAt(0))));
                calendarView.setSchemeDate(schemeList);
            }
        }
    }
//    设置标记内容
    private Calendar getSchemeCalendar(int y, int m, int d, int color, String text){
        Calendar calendar = new Calendar();
        calendar.setYear(y);
        calendar.setMonth(m);
        calendar.setDay(d);
        calendar.setSchemeColor(color);
        calendar.setScheme(text);
        return calendar;
    }
//    日期计划按日期顺序排序（正序）
    private ArrayList<PlantNote> sortData(ArrayList<PlantNote> plants){
        ArrayList<PlantNote> list = new ArrayList<>(plants.size());
        int[] indexs = new int[plants.size()];
        for (int i = 0; i < plants.size(); i++){
            indexs[i] = i;
        }
        for (int i = 0; i < plants.size()-1; i++){
            for (int j = i+1; j < plants.size(); j++){
                if (Integer.valueOf(plants.get(i).getDay()) > Integer.valueOf(plants.get(j).getDay())){
                    int temp = indexs[i];
                    indexs[i] = indexs[j];
                    indexs[j] = temp;
                }
            }
        }
        for (int i = 0; i < plants.size(); i++){
            list.add(plants.get(indexs[i]));
        }
        return list;
    }
//    删除或者发送
    private void deleteOrSend(final PlantNote plantNote){
        View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_plant_long_click,null);
        TextView btn_cancle = dialogView.findViewById(R.id.btn_cancel);
        TextView btn_delete = dialogView.findViewById(R.id.btn_delete);
        TextView btn_send = dialogView.findViewById(R.id.btn_send);
        if (EditActivity.widgetId == 0){
            btn_send.setVisibility(View.GONE);
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext()).setView(dialogView);
        final Dialog dialog = builder.create();
        dialog.setContentView(dialogView);
        dialog.show();
        btn_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sql.deletePlantById(plantNote.getId());
                Toast.makeText(getContext(), "删除成功~", Toast.LENGTH_SHORT).show();
                ListView list = EditActivity.menuList1;
                list.performItemClick(list.getChildAt(1),1,list.getItemIdAtPosition(1));
                dialog.dismiss();
            }
        });
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendTool.sendToWidget(getContext(), ClassFactory.getClass(EditActivity.size),
                        EditActivity.widgetId, SendTool.WIDGET_ACTION_PLANT,plantNote.getDay(),SendTool.TYPE_PLANT);
                EditActivity.widgetId = 0;
                EditActivity.size = "";
                dialog.dismiss();
                Toast.makeText(getContext(), "已发送到桌面小部件~", Toast.LENGTH_SHORT).show();
            }
        });
    }
    @Override
    public void onResume() {
        super.onResume();
//        更新日期计划预览列表
        data = getData();
        adapter.replaceAll(data);
        setScheme();
    }
}
